import { useEffect, useState } from 'react';
import {textbookService} from '../service/textbookService';

import { SimpleTreeView } from '@mui/x-tree-view/SimpleTreeView';
import { TreeItem } from '@mui/x-tree-view/TreeItem';

const LearnPage = () => {
  const [books, setBooks] = useState({});

  useEffect(() => {
    textbookService.getChapters().then(response => {
      const groupedChapters = response.reduce((acc, chapter) => {
        const { book_title, chapter_title } = chapter;
        if (!acc[book_title]) {
          acc[book_title] = [];
        }
        acc[book_title].push(chapter_title);
        return acc;
      }, {});
      setBooks(groupedChapters);

      // setChapters(response);
      console.log('Fetched chapters:', response.data)
    }).catch(error => {
      console.error('Error fetching chapters:', error);
    });
  }, []);

  const [expandedItems, setExpandedItems] = useState(['book-0']);

  const handleToggle = (event, itemIds) => {
    setExpandedItems(itemIds);
  };

  return (
    <div>
      <h1>Learn</h1>
      <SimpleTreeView expandedItems={expandedItems} onExpandedItemsChange={handleToggle}>
        {Object.keys(books).map((book, index) => (
          <TreeItem itemId={'book-' + String(index)} label={book}>
            {books[book].map((chapter, cpIndex) => (
              <TreeItem itemId={'chapter-' + String(index) + "-" + String(cpIndex)} label={chapter} />
            ))}
          </TreeItem>
        ))}
      </SimpleTreeView>
    </div>
  );
}

export default LearnPage;